# -*- coding:utf-8 -*-
import RedisHelper
from client.conf import setting 
import json
import time
from time import sleep
import threading
from client.plugins import plugin_api

class MonitorClient(object):
    def __init__(self):
        self.r = RedisHelper.RedisHelper()
        #从配置文件读取需要监控的客户端ip
        self.ip = setting.ClientIP
        
    def start(self):
        self.host_config=self.get_client_config()
        self.handle()
   
    def get_client_config(self):
        config_key = 'clientconfig::%s' %self.ip
        config = self.r.get(config_key)
        print config
        if config:
            config = json.loads(config)
        return config
    
    #从redis取出配置信息(服务名，插件名称，运行插件时间间隔),通过设定的时间戳来运行插件
    def handle(self):
        if self.host_config:
            #通while True 和 time.sleep(1)来计算秒数
            while True:
                for service,val in self.host_config.items():
                        #print service,val
                        #给每个服务加上一个时间戳,如果服务列表长度小于3,说明这个服务没有运行过，从0开始计时
                        if len(val)<3:
                            self.host_config[service].append(0)
                        plugin_name,interval,last_run_time = val
                        if time.time()-last_run_time < interval:
                                next_run_time = interval-(time.time() -last_run_time)
                                print "service:[%s] next run time is %s"% (service,next_run_time)
                        else:
                            print '---going to run che the [%s]'% service
                            self.host_config[service][2]=time.time()
                            #采用多线程避免阻塞导致时间不准确　
                            t = threading.Thread(target=self.call_plugin,args=(service,plugin_name))
                            t.start()
                time.sleep(1)
    
    #调用插件
    def call_plugin(self,service_name,plugin_name):
        #利用反射来执行插件,将字典数据发送给服务器
        func = getattr(plugin_api,plugin_name)
        service_data = func()
        report_to_server = {'host_ip':self.ip,
                            'service':service_name,
                            'data':service_data,
                            }
        self.r.publish(json.dumps(report_to_server))
        
        #print 'service [%s] res:%s'%(service_name,service_data)
